package com.wzj.uarmor.conf;

import com.wzj.uarmor.exception.BusinessException;
import com.wzj.uarmor.utils.ResponseStatus;
import com.wzj.uarmor.utils.ResponseVO;
import com.wzj.uarmor.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 异常统一处理
 *
 * @author Wanghw on 2022/8/12
 */
@RestControllerAdvice
@Slf4j
public class CustomerExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseVO businessExcetion(BusinessException businessException){
        log.error("统一的业务异常处理,异常信息",businessException);
        if(businessException.getResultMsgEnum()!= null){
            return ResultUtil.error(businessException.getResultMsgEnum());
        }
        return ResultUtil.error(ResponseStatus.ERROR.getCode(),businessException.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public ResponseVO otherExcetion(Exception exception){
        if( exception instanceof MethodArgumentNotValidException){
            log.error("参数校验有误",exception);
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) exception;
            List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
            StringBuilder msgBuilder = new StringBuilder();
            for (ObjectError allError : allErrors) {
                msgBuilder.append(allError.getDefaultMessage()).append("; ");
            }
            return ResultUtil.error("参数校验错误:" + msgBuilder.toString());
        }
        log.error("其他未知错误",exception);
        return ResultUtil.error(exception.getMessage());
    }
}
